package HomeService

import (
	"context"
	"database/sql"
	"gdshop-font-api-go/app/entity"
	"gdshop-font-api-go/app/request/HomeReq"
	"gdshop-font-api-go/library/response"
	"gdshop-font-api-go/library/tools"
	toolsDb "gdshop-font-api-go/library/tools/db"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/grand"
	"time"
)

func Forget(ctx context.Context, parames *HomeReq.Forget) *response.JsonResponse {
	// 判断验证码是否正确
	if !tools.VerifyVCode(parames.Mobile, parames.Vcode) {
		return response.FailByRequestMessage(nil, "验证码错误")
	}

	memberDb := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "member")
	memberModel := (*entity.Member)(nil)
	err := memberDb.Where(g.Map{
		"mobile": parames.Mobile,
	}).Struct(&memberModel)
	if err != nil {
		if err == sql.ErrNoRows {
			return response.FailByRequestMessage(nil, "账号不存在")
		}
		return response.FailByRequestMessage(nil, err.Error())
	}

	passwordSalt := grand.Letters(10)
	_, err2 := memberDb.Where(g.Map{
		"id": memberModel.Id,
	}).Update(g.Map{
		"password":      tools.EncryptPassword(parames.Password, passwordSalt),
		"password_salt": passwordSalt,
		"update_at":     uint(time.Now().Unix()),
	})
	if err2 != nil {
		return response.FailByRequestMessage(nil, err2.Error())
	}

	return response.SuccessByRequestMessage(nil, "找回密码成功")
}
